<template>
  <div class="wrap-container">
    <div class="search_box">
      <div class="search_tit">订单查询</div>
      <el-form :inline="true" label-position="left" label-width="76px">
        <el-form-item label="用户id">
          <el-input v-model="queryParams.userId" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="queryParams.mobile" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="优惠券名称">
          <el-input v-model="queryParams.name" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select v-model="queryParams.discountType" placeholder="请选择" clearable filterable>
            <el-option
              v-for="dict in dict?.type?.coupon_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单日期">
          <el-date-picker
            v-model="queryParams.orderDate"
            type="date"
            placeholder="请选择订单日期"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <div class="flex justify-end">
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="table_box">
      <div class="tabs_box">
        <el-tabs v-model="tabsVal" @tab-change="handleClick">
          <el-tab-pane
            :label="`${item.label}`"
            :name="item.value"
            v-for="item in tabsList"
            :key="item.value"
          >
            <template #label>
              <span
                :class="{
                  tabs_animation: item.value == '8' || item.value == '9',
                }"
              >
                {{ item.label }}
                <el-badge
                  v-if="item.count != 0"
                  :value="item.count"
                  class="item"
                  type="danger"
                ></el-badge>
              </span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column label="订单号" prop="orderNo" width="180" />
        <el-table-column label="用户id" prop="userId" width="180" />
        <el-table-column label="手机号" prop="mobile" width="120" />
        <el-table-column label="优惠名称" prop="couponsName" width="240" show-overflow-tooltip />
        <el-table-column label="优惠类型" width="100">
          <template #default="{ row }">
            <div v-for="item in dict?.type?.coupon_type" :key="item.value">
              <div v-if="item.value == String(row.discountType)">
                {{ item.label }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="使用条件" width="140">
          <template #default="{ row }">
            <span v-if="row.discountType === 3">满{{ row.useAmount }}减{{ row.moneyAmount }}</span>
            <span v-else>无门槛</span>
          </template>
        </el-table-column>
        <el-table-column label="购买数量" prop="quantity" width="120" />
        <el-table-column label="支付金额" prop="payAmount" width="120" />
        <el-table-column label="订单状态" prop="state" width="120">
          <template #default="{ row }">
            <span style="color: #f61406" v-if="row.state == 0">待使用</span>
            <span style="color: #050ef1" v-else-if="row.state == 1">已使用</span>
            <span style="color: #ea6d13" v-else-if="row.state == 2">已退款</span>
            <span style="color: #a6a6a6" v-else-if="row.state == 3">已过期</span>
            <span style="color: #e78549" v-else-if="row.state == 4">部分退款</span>
          </template>
        </el-table-column>
        <el-table-column label="下单日期" prop="createTime" width="190" />
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <div class="table_btn flex">
              <el-button
                class="primary_text"
                type="text"
                v-hasPermi="['sys:couponOrder:btn_view']"
                @click="handleDetail(row.id)"
                >详情</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCouponsOrder, getCouponsOrderCount } from '@/api/order/coupon'
import { deleteOrder } from '@/api/order/order'
import { useDict } from '@/utils/dict'

defineOptions({
  name: 'CouponList',
})

interface QueryParams {
  pageNum: number
  pageSize: number
  userId: string | null
  mobile: string | null
  name: string | null
  discountType: string | null
  orderDate: string | null
}

interface TabsItem {
  label: string
  value: string
  count: number
}

interface TableItem {
  id: number
  orderNo: string
  userId: number
  mobile: string
  couponsName: string
  discountType: number
  useAmount: number
  moneyAmount: number
  quantity: number
  payAmount: number
  state: number
  createTime: string
}

const { dict }: any = useDict({
  dicts: [],
})
// const { proxy } = getCurrentInstance() as any
const router = useRouter()

const loading = ref(false)

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  userId: null,
  mobile: null,
  name: null,
  discountType: null,
  orderDate: null,
})

const total = ref(0)

const tabsList = ref<TabsItem[]>([
  { label: '全部', value: '0', count: 0 },
  { label: '待使用', value: '1', count: 0 },
  { label: '已使用', value: '2', count: 0 },
  { label: '已退款', value: '3', count: 0 },
])

const tabsVal = ref('0')
const tableData = ref<TableItem[]>([])
const multipleSelection = ref<TableItem[]>([]) //表格多选的值

// 订单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getCouponsOrder({
      orderStatus: tabsVal.value,
      ...queryParams,
    })
    tableData.value = res.rows
    total.value = res.total
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error(error)
  }
}

// 订单统计
const getCount = async () => {
  try {
    const { data } = await getCouponsOrderCount(queryParams)
    if (tabsList.value[0])
      tabsList.value[0].count = data.waitCount + data.usedCount + data.refundCount
    if (tabsList.value[1]) tabsList.value[1].count = data.waitCount
    if (tabsList.value[2]) tabsList.value[2].count = data.usedCount
    if (tabsList.value[3]) tabsList.value[3].count = data.refundCount
  } catch (error) {
    console.error(error)
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
  getCount()
}

// 重置
const reset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    mobile: null,
    name: null,
    discountType: null,
    orderDate: null,
  })
  getList()
  getCount()
}

// 选项卡切换
const handleClick = () => {
  queryParams.pageNum = 1
  getList()
  getCount()
}

// 表格多选
const handleSelectionChange = (val: TableItem[]) => {
  multipleSelection.value = val
}

// 查看详情
const handleDetail = (id: number) => {
  router.push({
    path: '/order/couponOrderDetail',
    query: { id },
  })
}

// 删除
const handleDel = (type: number, id?: number) => {
  let ids = ''
  if (type == 1) {
    ids = multipleSelection.value.map((item) => item.id).join(',')
  } else {
    ids = id?.toString() || ''
  }
  if (ids == '') {
    ElMessage.error('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('是否确认删除选中的数据项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await deleteOrder(ids)
        getList()
        getCount()
        ElMessage.success('删除成功')
      } catch (error) {
        console.error(error)
      }
    })
    .catch(() => {})
}

const formatter = (row: any, column: any, cellValue: any) => {
  // 如果单元格值为空或为 null，返回 '--'
  return cellValue || '--'
}

onMounted(() => {
  getList()
  getCount()
})
</script>

<style lang="scss" scoped>
.search_box {
  padding-bottom: 0;
}
.table_box {
  position: relative;
  .tabs_box {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-bottom: 15px;
    padding-top: 6px;
    :deep(.el-tabs) {
      flex: 1;
      .el-tabs__header {
        margin: 0;
      }
      .tabs_animation {
        // animation: blink 1s infinite; /* 应用动画 */
      }
    }
  }
  .handle_btn {
    margin-left: 35px;
  }
}
:deep(.el-table .el-table__body td .cell .line-limit-length:empty::after) {
  content: '--';
}
.badge_animation {
  animation: blink 1.5s infinite;
}
@keyframes bounce {
  0%,
  100% {
    top: 0;
    transform: translateY(0);
  }
  50% {
    transform: translateY(-8px); /* 调整这个值以改变跳动的高度 */
  }
}
@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
</style>
